<?php
declare (strict_types = 1);

namespace app\order\model;

use app\api\model\WxApi;
use app\common\model\BaseModel;
use app\common\model\Config;
use app\common\self\MyJob;
use app\live\model\LiveBroadcastGoods;
use app\live\model\LiveBroadcastInfo;
use app\live\model\LiveBroadcastOrder;
use app\live\model\LiveMiaoLog;
use app\mall\model\ActivityLog;
use app\mall\model\Goods;
use app\mall\model\GoodsAttr;
use app\myself\WeixinPay;
use app\user\model\District;
use app\user\model\MiaoLog;
use app\user\model\User;
use app\user\model\UserAddress;
use app\user\model\UserLevel;
use app\user\model\UserShareOrder;
use app\user\model\UserVolume;
use app\user\model\UserVolumeLog;
use app\user\model\UserWallet;
use app\user\model\WalletOperationLog;
use app\common\self\SelfRedis;
use app\myself\Bc;
use app\service\model\Express;
use League\Flysystem\Exception;
use think\Db;
use think\facade\Log;
use think\Model;
use think\Request;

/**
 * @mixin \think\Model
 */
class Order extends BaseModel
{
    public $page = '';//分页数据
    public $count = '';//数据总数
    public $error = '';//报错

    public $statusObj = [
        '1' => '待付款',
        '2' => '待发货',
        '3' => '待收货',
        '4' => '已收货',
        '5' => '已完成'
    ];

    // 配送方式
    public $deliverObj = [
        '1' => '快递配送',
        '2' => '到店自提',
        '3' => '同城配送'
    ];

    // 售后文字提示
    public $serviceObj = [   // 没有售后服务0，1已申请等待审核， 2处理售后服务中，3 售后处理完毕
        '',
        '已申请等待审核',
        '处理售后中',
        '售后处理完成',
        '已被商家拒绝售后'
    ];

    //数据预处理 - 订单实收金额
    public function getTotalAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    //数据预处理- 运费金额
    public function getFreightAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    //数据预处理- 购物券金额
    public function getVolumeAttr($value)
    {
        return number_format($value/100,2,'.','');
    }

    // 拿取订单列表
    public function getList($get,$user)
    {
        $oredr = 'add_time desc';
        $where = [['is_delete','=',0],['uid','=',$user->id],['is_display','=',1]];
        $status = isset($get['status']) ? $get['status'] : -1;
        if($status > 0){
            // 如果为待评价
            if($status == 4){
                $where[] = ['is_appraise','=',0];
                $where[] = ['status','>=',$status];
            }else{
                $where[] = ['status','=',$status];
            }
        }
        $this->queryList($get,'id,order_sn,total,type,add_time,status,is_appraise',$where,$oredr);
        foreach($this->modelList as $k => $v){
            // 拿取到订单详情页面
            if($v->oneOrderInfo && $v->oneOrderInfo['json'] && isset($v->oneOrderInfo['json']['good_attr'])){
                $this->list['data'][$k]['good_attr'] = $v->oneOrderInfo['json']['good_attr'];
                if(isset($v->oneOrderInfo['json']['good_attr']['img'])){
                    $this->list['data'][$k]['good_attr']['img'] = checkFile($v->oneOrderInfo['json']['good_attr']['img']) ? getApiDominUrl($v->oneOrderInfo['json']['good_attr']['img']) : getHostDominUrl($v->oneOrderInfo['json']['good_attr']['img']);
                }
                if($this->list['data'][$k]['good_attr']['valjson'] && is_array($this->list['data'][$k]['good_attr']['valjson'])){
                    $str = '';$index = 1;
                    foreach($this->list['data'][$k]['good_attr']['valjson'] as $ik =>$i){
                        $str .= $ik."：".$i.($index != count($this->list['data'][$k]['good_attr']['valjson']) ? ',' : '');
                        $index++;
                    }
                    $this->list['data'][$k]['good_attr']['valjson'] = $str;
                }
                $this->list['data'][$k]['num'] = isset($v->oneOrderInfo['json']['num']) ? $v->oneOrderInfo['json']['num'] : 1;
                $this->list['data'][$k]['title'] = isset($v->oneOrderInfo['json']['goods']) ? $v->oneOrderInfo['json']['goods']['title'] : '';
                $this->list['data'][$k]['goods_id'] = isset($v->oneOrderInfo['json']['goods']) ? $v->oneOrderInfo['json']['goods']['id'] : '';
            }
        }
    }

    // 拿取单条订单-订单详情
    public function getOne($get,$user)
    {
        // 拿取到单条订单
        $id = isset($get['id']) ? $get['id'] : -1;
        if(!$id|| $id < 0)
            return retu_json(400,'id不得为空');
        if(!$one = $this->where(['uid'=>$user->id,'id'=>$id])->find())  // $user->id
            return retu_json(400,'没有该记录');
        $districtModel = new District();
        if(!$one->oneUserAddress)
            return retu_json(400,'订单错误-地址错误');
        $addressList = $one->oneUserAddress->toArray();
        $address_list = $districtModel->getAddressStr($addressList);
        if(!$one->manyOrderGood || count($one->manyOrderGood) == 0)
            return retu_json(400,'订单错误-商品订单错误');
        $orderGoodList = $one->manyOrderGood[0]->toArray();
        // 默认为不可以申请售后 申请售后 条件： 已付款之后 且 商品没有在售后处理中
        $isService = $one->status > 1 && $one->status != 5 ? 1 : 0;
        // 获取 订单详情
        $good_list = [];
        if($one->oneOrderInfo){
            $str = '';
            $item = $one->oneOrderInfo['json']['good_attr'];
            if($item['valjson']){
                foreach($item['valjson'] as $k => $v)
                    $str .=     $k."：".$v." ";
            }
            $item['valjson'] = $str;
            $item['tips'] = $this->serviceObj[$one->service];
            $item['goods_name'] = $one->oneOrderInfo['json']['goods']['name'];
            $item['goods_title'] = $one->oneOrderInfo['json']['goods']['title'];
            $item['num'] = $orderGoodList['num'];
            $item['is_service'] = $isService;
            $item['order_goods_id'] = $orderGoodList['id'];
            $good_list[] = $item;
        }
        $express_desc = false;
        // 是否有该物流信息
        if($one->oneExpress){
            $express_desc = [
                'express_sn' => $one->oneExpress->express_sn,
                'desc' => $one->oneExpress->desc,
                'upd_time' =>  date('Y-m-d H:i:s',$one->oneExpress->upd_time)
            ];
        }


        $list = [
            'order_sn' => $one->order_sn,
            'add_time' => $one->add_time,
            'status' => $one->status,
            'total' => $one->total,
            'price' => $orderGoodList['price'],
            'volume' => $one->volume,
            'freight' => $one->freight,
            'is_service'=> $isService, // 是否可以申请售后
            'remarks' => $one->remarks,
            'deliver' => isset($this->deliverObj[$one->deliver]) ? $this->deliverObj[$one->deliver] : $one->deliver,
            'purchase_money' => $orderGoodList['purchase_money'],
            // 收货地址
            'address' =>[
                'id' => $addressList['id'],
                'uid' => $addressList['id'],
                'address_str' => implode(' ',$address_list)." ".$addressList['address'],
                'tel' => $addressList['tel'],
                "name" => $addressList['name']
            ],
            // 保留商品信息
            'good_list' => $good_list,
            // 物流信息
            'express_desc' => $express_desc
        ];
        return $list;
    }

    // 订单取消
    public function checkCancel($user)
    {
        $request  = request();
        $id = $request->param('id',-1);
        if(!$id|| $id < 0)
            return retu_json(400,'id不得为空');
        if(!$one = $this->where(['uid'=>$user->id,'id'=>$id])->find())  // $user->id
            return retu_json(400,'没有该记录');
        if($one->status != 1)
            return retu_json(400,'只有待付款的才能取消');
        // 开启事务
        $this::startTrans();
        try{
            Log::write('订单取消开始----',__FUNCTION__);
            // 判断类型是否为活动且 当前活动拼团有该id
            $whereDelete = [['oid','=',$one->id],['uid','=',$user->id],['pay_status','=',0]];
            if($one['type'] == 2 && $activityLogModel = ActivityLog::where($whereDelete)->find()){
                ActivityLog::where('id',$activityLogModel->id)->delete();
//                $activityLogModel->delete();
                Log::write($activityLogModel,__FUNCTION__.'订单取消开始----删除记录');
            }
            $one->status = 0;
            # 拿取到当前订单的  订单商品
            $OrderGoodsModel = OrderGoods::where('order_id',$one->id)->find();
            // 获取到 订单对应的商品
            $goodsModel = Goods::find($OrderGoodsModel->goods_id);
            // 如果是拍下减库存 ，需要加回去
            if($goodsModel->is_stock == 1){
//                $goodsModel->stock +=  $OrderGoodsModel->num;
                // 找到商品规格
                $goodsAttrModel = GoodsAttr::find($OrderGoodsModel->attr_id);
                if($goodsAttrModel){
//                    $goodsAttrModel->stock += $OrderGoodsModel->num;
                    GoodsAttr::where('id',$goodsAttrModel->id)->update([
                        'stock' =>  $goodsAttrModel->stock + $OrderGoodsModel->num
                    ]);
//                    $goodsAttrModel->save();
                }
//                $goodsModel->save();
                Goods::where('id',$goodsModel->id)->update([
                    'stock' =>  $goodsModel->stock + $OrderGoodsModel->num
                ]);
            }
            $ok = Order::where('id',$one->id)->update([
                'status' => 0
            ]);
            UserShareOrder::where('oid',$one->id)->update([
                'status' => 0
            ]);
//            $ok = $one->save();
            if(!$ok)
                throw new Exception('数据错误');
            // 提交事务
            Log::write('订单取消开始----处理完毕',__FUNCTION__);
            $this::commit();
            return retu_json(200,'订单取消ok');
        }catch (Exception $e){
            $this::rollback();
            return retu_json(400,'麻烦重新尝试');
        }
    }

    // 删除
    public function del($user)
    {
        $request  = request();
        $id = $request->param('id',-1);
        if(!$id|| $id < 0)
            return retu_json(400,'id不得为空');
        if(!$one = $this->where(['uid'=>$user->id,'id'=>$id])->find())  // $user->id
            return retu_json(400,'没有该记录');
        // 状态如果在1-4之间则不能删除
        if($one->status > 0 && $one->status < 5)
            return retu_json(400,'只能删除已取消或者已完成的订单');
        $bool = $this->where('id',$one->id)->update([
            'is_display' => 0
        ]);
        if(!$bool)
            return retu_json(400,'状态错误');
        return $bool;
    }

    // 用户点击确认收货
    public function checkReceipt($user)
    {
        $request  = request();
        $id = $request->param('id',-1);
        if(!$id|| $id < 0)
            return retu_json(400,'id不得为空');
        if(!$one = $this->where(['uid'=>$user->id,'id'=>$id])->find())  // $user->id
            return retu_json(400,'没有该记录');
        if($one->status != 3)
            return retu_json(400,'只有待收货的才可以确认');
        $this::startTrans();
        try{
            # 判断是否为 拼团  且 入团
            $orderInfoModel = OrderInfo::where('oid',$one->id)->find();
            if($orderInfoModel && $orderInfoModel->switch_num == 3){
                $ActivityLogModel = ActivityLog::where('oid',$one->id)->find();
                # 查找父级 必须有父级id
                if($ActivityLogModel && $ActivityLogModel->pid > 0 && $ActivityLogPModel = ActivityLog::find($ActivityLogModel->pid)){
                    if($ActivityLogPModel->partake && $listObj = $ActivityLogPModel->partake){
                        $newData = false;
                        # 迭代循环, 需要没有结算 且等于当前
                        foreach($listObj as $k => &$item){
                            if($item['uid'] == $one->uid && $item['status'] == 0){
                                $item['status']  = 1;
                                $newData = $item;
                                $listObj[$k]['status'] = 1;
                                break;
                            }
                        }
                        if($newData && $newData['miao'] > 0){
                            # 改变状态 并且 修改 状态
                            ActivityLog::where('id',$ActivityLogPModel->id)->update([
                                'partake' => json_encode($listObj)
                            ]);
                            # 改变 喵呗  并 插入记录   
                            $UserWalletPmodel = UserWallet::where('uid',$ActivityLogPModel->uid)->find();
                            UserWallet::where('uid',$ActivityLogPModel->uid)->update([
                                'pre_miao' => $UserWalletPmodel->pre_miao -  $newData['miao'] > 0 ? $UserWalletPmodel->pre_miao -  $newData['miao'] : 0,
                                'miao' => $UserWalletPmodel->miao + $newData['miao'],
                                'miaos' => $UserWalletPmodel->miaos + $newData['miao']
                            ]);
                            # 记录 钱包操作记录 -  此处需要记录的有三条
                            $wallLogData = [];$time = time();
                            # 记录  -  扣掉 预估喵呗
                            $wallLogData[] = [
                                'status' => 2,
                                'type' => 2,
                                'uid' => $UserWalletPmodel->uid,
                                'reward' => $newData['miao'],
                                'extend' => 'ActivityLog',
                                'extend_id' => $ActivityLogPModel->id,
                                'describe' => '用户-订单结算-拼团-下级团员处理-扣除待预估喵呗',
                                'add_time' => $time
                            ];
                            # 记录  -   增加的喵呗
                            $wallLogData[] = [
                                'status' => 1,
                                'type' => 2,
                                'uid' => $UserWalletPmodel->uid,
                                'reward' => $newData['miao'],
                                'extend' => 'ActivityLog',
                                'extend_id' => $ActivityLogPModel->id,
                                'describe' => '用户-订单结算-拼团-下级团员处理-增加喵呗',
                                'add_time' => $time
                            ];
                            # 记录  -  -增加累计喵呗
                            $wallLogData[] = [
                                'status' => 1,
                                'type' => 2,
                                'uid' => $UserWalletPmodel->uid,
                                'reward' => $newData['miao'],
                                'extend' => 'ActivityLog',
                                'extend_id' => $ActivityLogPModel->id,
                                'describe' => '用户-订单结算-拼团-下级团员处理-增加累计喵呗',
                                'add_time' => $time
                            ];
                            # 喵呗 更改状态 状态为 预估 且 当前订单号 和 父级uid  拼团
                            $miaoLogUId = MiaoLog::where(['status' => 1, 'uid' => $ActivityLogPModel->uid,'oid' => $ActivityLogPModel->oid,'type' => 2,'reward' => $newData['miao']])->update([
                                'status' => 3 // 入账
                            ]);
                            # 喵呗更改错误
                            if(!$miaoLogUId) return retu_json(400,'错误');
                            WalletOperationLog::insertAll($wallLogData);
                        }
                    }
                }
            }
            $one->status = 4;
            $one->receive_time = time();
            $ok = $one->save();
            #  确认收货
            UserShareOrder::where('oid',$one->id)->update([
                'status' => 4
            ]);
            if(!$ok)
                return retu_json(400,'麻烦重新尝试');
            $this::commit();
            return retu_json(200,'确认收货ok');
        }catch(Exception $e){
            return retu_json(200,'网络错误，麻烦重新尝试');
        }
    }

    // 用户 付款
    public function pendingPayment($user)
    {
        $request  = request();
        $id = $request->param('id',-1);
        if(!$id|| $id < 0)
            return retu_json(400,'id不得为空');
        if(!$one = $this->where(['uid'=>$user->id,'id'=>$id])->find())  // $user->id
            return retu_json(400,'没有该记录');
        if($one->status != 1)
            return retu_json(400,'只有待付款的才可以确认');
        // 限流

        $sr = new SelfRedis();
        $sr->redis->select(5);
        if($sr->redis->getNx('order_pendingPayment_'.$user->id))
            return retu_json(400,'等待1秒后尝试');
        // 限流  - 单个用户 2秒只能生成一笔订单 防止 产生多个订单号
        $sr->redis->setNx('order_pendingPayment_'.$user->id,$one->order_sn,3);
        // 调起微信支付
        $one->pay_num += 1;

        // 判断购物券余额
        if($one->volume && $one->volume > 0){
            $wallet = UserWallet::where('uid',$user->id)->find();
            // 如果当前使用购物券余额 大于 钱包余额
            if($one->volume * 100 > $wallet->volume_balance){
                $this->where('id',$one->id)->update([
                    'status' => 0
                ]);
                return retu_json(400,'抱歉此订单需要抵扣的购物券已超过购物券，麻烦重新下单');
            }
        }

        // 订单号
        $orn = $one->order_sn.$one->pay_num;
        $money = $one->total;
        if($money <= 0) $money = 0;
        // 调用微信支付返回信息
        $a = new WeixinPay($user->openid,$orn,'订单支付',$money); // $money
        $pay = $a->pay(); //下单获取返回值
        if(!$pay || !$pay['code'])
            return retu_json(400,isset($pay['msg']) ? $pay['msg'] : '麻烦重新尝试');
        if(isset($pay['data']['appId']))
            unset($pay['data']['appId']);
        $pay['data']['orderid'] = $orn;

        $this::startTrans();
        try{
            $this::where('id',$one->id)->update([
                'pay_num' => $one->pay_num + 1 // 将支付订单加1
            ]);
            $this::commit();
            return $pay;
        }catch (Exception $e){
            $this::rollback();
            return retu_json(400,'操作错误');
        }
    }

    /*
     * 获取用户订单状态&数量
     */
    public function getOrderNumOnStatus($id){
        try{
            $where = ['uid' => $id,'is_delete'=>0];
            $field = 'count(IF(status=1,true,null)) as pay_num,count(IF(status=2,true,null)) as send_num,count(IF(status=3,true,null)) as receive_num,count(IF(status>=5 and is_appraise=0,true,null)) as appraise_num,count(IF(status=6 or status=8,true,null)) as service_num';
            $item = $this->where($where)->field($field)->find();
            $orders = empty($item) ? array():$item->toArray();

            return $orders;
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }


    /**
     * 插入记录生成的模板
     */
    public function getDefaultData()
    {
        return [

        ];
    }

    /**
     * @param $dataNotify  此处是微信回到   回调进行处理  不是真正的开始处理逻辑  开始处理逻辑在下方
     * @return array  返回数组
     */
    public function payModelNotify($dataNotify){
        $time = time();
        $data = $dataNotify['data'];
        // 返回的数据
        $list = ['bool' => false, 'data' => $data,'msg'=> 'ok'];

        //购物券回调
        if(substr($dataNotify['data']['out_trade_no'],0,1) == 'V'){
            $VolumeNotify = (new UserVolume())->volumeNotify($dataNotify);
            return $VolumeNotify;
        }

        $orn = substr($dataNotify['data']['out_trade_no'],0,20);
        // 回调开始
        // 第一步 微信回调 不管 怎么样都要存储字段
        $payLogModel = new PayLog();
        $payLogInfo = $payLogModel->where(['orn'=>$dataNotify['data']['out_trade_no']])->find();
        if(!empty($payLogInfo)){
            $payLogId = $payLogInfo['id'];
            $payLogModel->where(['id'=>$payLogId])->update(['response' => json_encode(['data'=>$data,'wechat_str'=>$dataNotify['wechat_str']]), 'openid' => $data['openid'], 'add_time' => time(), 'ip' => $dataNotify['ip'],'explain'=>'微信支付已回调']);
        }else{
            $payLogData = [
                'explain' => '微信支付已回调',
                'type' => 1,// 支付回调
                'request' => '', // 回调数据
                'response' => json_encode(['data'=>$data,'wechat_str'=>$dataNotify['wechat_str']]), // 响应数据
                'add_time' => $time,
                'status' => 0, // 默认没有处理
                'openid' => $data['openid'], // 微信openid
                'orn' => $dataNotify['data']['out_trade_no'],//  订单号
                'ip' => $dataNotify['ip'] // ip 地址
            ];
            $payLogId = $payLogModel->insertGetId($payLogData);
        }

//        Log::write($payLogData,'info');

        // 插入记录
        if(!$payLogId){
            Log::write("时间：".date("Y-m-d H:i:s")."，订单号：".$orn."，插入历史请求错误",'info');
            return retu_json(400,'插入记录失败');
        }

        // 拿取数据 -- 开始验证 订单号
        if(!$orderOrnModel = $this->where('order_sn',$orn)->find()){$list['msg'] = '没有该订单号';return $list;}
        // 如果不等于微信支付 ||  状态 为未完成
        if($orderOrnModel->pay_type != 1 || $orderOrnModel->status != 1){$list['msg'] = '该订单已完成或者不是微信支付，订单id：'.$orderOrnModel->id;return $list;}
        // 订单详情
        if(!$orderInfoModel = OrderInfo::where('oid',$orderOrnModel->id)->find()){$list['msg'] = '没有订单详情,订单id：'.$orderOrnModel->id;return $list;}
        // 没有订单详情判断类型
        if($orderInfoModel->switch_num <= 0){$list['msg'] = '没有订单详情回调判断类型,订单详情id：'.$orderInfoModel->id;return $list;}
        // 用户 - 错误
        if(!$userModel = User::where('openid',$data['openid'])->find()){$list['msg'] = '没有该用户openid';return $list;}
        Log::write('----开始你的表演----'.$orderOrnModel->order_sn,'huiDiao');
        // 调用统一处理逻辑  需要走下面的处理
        $list = $this->completeOrder([
            'orderOrnModel' => $orderOrnModel,
            'orderInfoModel' => $orderInfoModel,
            'userModel' => $userModel
        ]);
        return $list;
    }

    /**
     *  完成订单后的处理逻辑
     */
    public function completeOrder($ModelsList = [],$bool = true)
    {
        echo 666666;
        exit;
        $list = [
            'bool' => true,
            'msg' => 'ok'
        ];


        $orderInfoModel = $ModelsList['orderInfoModel'];
        $orderOrnModel = $ModelsList['orderOrnModel'];
        $userModel = $ModelsList['userModel'];



        // 模型开始 订单，订单详情，用户，喵呗历史模型
        $miaoLogModel = new MiaoLog();



        $orderGoods = OrderGoods::field('order_id,goods_id,price,volume,total,purchase_money,is_sale,is_team')->where(['order_id'=>$orderOrnModel->id])->select();
        // 获取到 用户等级列表
        $userLevelAllList =  (new UserLevel())->allGetList();

        # 算出 所有的 分享/分销的金额  和   累计消费  累计金额
        $shareOrder = [];$teamOrder = [];//分销/团队订单
        $shareAmount = 0;$teamAmount = 0;
        if(!empty($orderGoods)){
            foreach($orderGoods as $k=>$v){
                if($v['is_sale'] == 1) $shareOrder[] = $v;$shareAmount += $v['price'];
                if($v['is_team'] == 1 ) $teamOrder[] = $v;$teamAmount += $v['total'];
            }
        }

        $time = time();

        $bc = new Bc();

        $this::startTrans();
        try{
            Log::write('----开始处理逻辑----'.$orderOrnModel->order_sn,'huiDiao');

            $bool = false;
            // 开启事务
//            $this::startTrans();
            // 基础操作开始
            // 更新时间-订单中的信息 // 设置状态 已完成
            $orderOrnModel->pay_time =  $time;$orderOrnModel->status = 2;$orderOrnModel->save();
            // 如果有使用  购物券  需要减去
            if($orderOrnModel->volume > 0){
                $UserWalletModel = new UserWallet();
                $uid_userWalletModel = $UserWalletModel->where('uid',$orderOrnModel->uid)->lock(true)->find();
                if($uid_userWalletModel){
                    // 购物券小于 直接 返回
                    if($uid_userWalletModel->volume_balance < $orderOrnModel->volume){$list['bool'] = false;$list['msg'] = '当前购物券余额小于 需要支付的购物券余额';return $list;}
                    # 此处使用  订单购物券余额--预处理数据 需要转换
                    $linshi_volume = $uid_userWalletModel->volume_balance;
                    $uid_userWalletModel->volume_balance = $uid_userWalletModel->volume_balance - $orderOrnModel->volume * 100;$uid_userWalletModel->save();
                    # 所有操作  钱包 都需要走钱包表
                    $WalletOperationLogData = ['uid'=>$userModel->id,'reward'=> $orderOrnModel->volume * 100,'status'=>2,'type'=>3,'extend'=>'order','extend_id'=>$orderOrnModel->id,'describe'=>'订单支付-扣除购物券','add_time'=>$time];
                    WalletOperationLog::insertGetId($WalletOperationLogData);
                    # 此处使用购物券  需要插入到购物券历史记录
                    UserVolumeLog::insertGetId(['type'=>1,'uid'=>$userModel->id,'price'=>$orderOrnModel->volume * 100,'balance'=>$linshi_volume,'add_time'=>$time,'oid'=>$orderOrnModel->id]);
//                    $userVolumeLogData = ['type' => 1, 'uid' => $userModel->id, 'vid' => $uid_userWalletModel->id, 'relation_id' => $orderOrnModel->id, 'price' => $orderOrnModel->volume, 'balance' => $uid_userWalletModel->volume_balance, 'add_time' => $time, 'oid' => $orderOrnModel->id];
//                    $UserVolumeLogId = UserVolumeLog::insertGetId($userVolumeLogData);
//                    if(!$UserVolumeLogId){$list['bool'] = false;$list['msg'] = '购物券-失败';return $list;}
                    Log::write("\t\t订单id".$orderOrnModel->id."\r\n记录消费券-处理完毕",'huiDiao');
                }
            }

            $miaoLogData = [
                'oid' => $orderOrnModel->id,
                'status' => 1,
                'add_time' => time()
            ];
            // 处理逻辑开始
            switch($orderInfoModel->switch_num){
                // 1. 普通商品 - 将订单 状态更新  并且  插入喵呗记录 即可
                case 1:
                    Log::write("\t\t订单id".$orderOrnModel->id."\r\n普通商品处理完毕",'huiDiao');
                    break;
                // 拼团 - 创建
                case 2:
                    ActivityLog::where('oid',$orderOrnModel->id)->update(['pay_status'=> 1]);
                    Log::write("\t\t订单id".$orderOrnModel->id."\r\n拼团创建处理完毕",'huiDiao');
                    break;
                // 入团-创建 - 且获取到上级的团
                case 3:
                    // 修改自己的
                    ActivityLog::where('oid',$orderOrnModel->id)->update(['pay_status'=> 1]);
                    $activityLogOneModel = ActivityLog::where('oid',$orderOrnModel->id)->find();
                    if($activityLogOneModel){
                        // 拿取到父级的 支付状态必须为1
                        $activityLogPModel = ActivityLog::where(['id'=>$activityLogOneModel->pid,'pay_status'=>1])->find();
                        // 当前人数
                        $num = $activityLogPModel->nums;
                        // 佣金
                        $miao = $activityLogPModel['type'] == 2 ? $activityLogPModel->content[$num] * 100 : $activityLogPModel->content[$num] / 100 * $orderOrnModel->total;
                        // 拿取到历史数据, 如果没有则拼接
                        $log_list = $activityLogPModel->partake ? $activityLogPModel->partake : [];
                        # 记录状态为 status 0  表示 没有结算过  ， 后台 和  用户点击时需要结算处理
                        $log_list[] = ['uid'=>$userModel->id,'oid'=>$orderOrnModel->id,'miao'=>$miao,'status'=>0];
                        ActivityLog::where('id',$activityLogPModel->id)->update([
                            'nums' => $activityLogPModel->nums + 1, // 人数加1
                            'miao' => $activityLogPModel->miao + $miao,
                            'partake' => json_encode($log_list),
                            'astatus' => $num + 1 == $activityLogPModel->num ? 1 : 0 // 如果参与人数已达标   那么则完成该活动
                        ]);
                        // 写入入团 - 喵呗记录  - 团主 -
                        MiaoLog::insertGetId([
                            'type' => 2, // 类型  拼团
                            'reward' => $miao, // 喵呗奖励
                            'uid' =>  $activityLogPModel->uid, 'oid' => $activityLogPModel->oid, 'add_time' => $time, // 用户id, 订单号，喵呗奖励
                            'money' => $orderOrnModel->total
                        ]);
                        # 所有操作钱包表  都需要
                        $userWalletOneModel = UserWallet::where('uid', $activityLogPModel->uid)->lock(true)->find();
                        if($userWalletOneModel){
                            $userWalletOneModel->pre_miao += $miao;$userWalletOneModel->save();
                            # 钱包记录
                            $WalletOperationLogData = ['uid'=>$userModel->id,'reward'=> $miao,'status'=>1,'type'=>2,'extend'=>'order','extend_id'=>$orderOrnModel->id,'describe'=>'订单支付-入团','add_time'=>$time];
                            WalletOperationLog::insertGetId($WalletOperationLogData);
                        }
                        Log::write("\t\t订单id".$orderOrnModel->id."\r\n拼团创建-入团且修改上级的团处理-处理完毕",'huiDiao');
                    }
                    break;
                // 4 视频 - 关联- 分享 商品 4  || 5 商品分享-商品关联  || 6 直播列表-直播分享购买
                case 4 || 5 || 6:
                    $share_strs = [
                        4 => '视频分享-',
                        5 => '商品分享-',
                        6 => '直播中-直播购买'
                    ];
                    $desc_str = '处理'.$share_strs[$orderInfoModel->switch_num];
                    $userShareOrderOneModel = UserShareOrder::where('oid',$orderOrnModel->id)->find();
                    //Log::write('用户-视频-关联-分享商品', 'type_4');
//                    Log::write($orderInfoModel['json'],'用户-视频-关联-分享商品');

                    #订单中包含分享用户&包含分销商品 - 分享分佣 = 商品价格*分享者分享赚比例 - 商品价格*购买者自购省比例
                    // 判断是否有上级 $orderInfoModel['json'] 需要使用这种去拿取数据
                    #if ( ($orderInfoModel['json'] && isset($orderInfoModel['json']['data_list']['puid'])) || $puid) {

                    $total  = 0;$puid_num = 0;

                    // 视频分享 或者 商品分享走此处
                    if ($orderInfoModel['json'] && isset($orderInfoModel['json']['data_list']['puid'])) {
                        $puid = $orderInfoModel['json']['data_list']['puid'];
                        $puidUser = User::find($puid);
                        // 体验掌柜 不得分享  需要层级大于 1  或者 is_proceeds == 1 视频收益权限开通
                        // $is_proceeds = $puidUser->level > 1 || $puidUser->is_proceeds == 1 ? 1 : 0;
                        // 上级 等级 大于  当前级别 且开通了
                        // if ($puidUser && isset($userLevelAllList[$puidUser->level]) && $puidUser->level > $userModel->level && $is_proceeds >= 1) {

                        // 条件  1. 开通了购物券 必须
                        //  当前等级大于下级  或者  当前等级和下级等级等于1，且下级没有开通购物券

                        // 当前等级和下级等级等于1，且下级没有开通购物券
                        $volumeBool = $userModel->level == 1 && $puidUser->level == 1 && $userModel->is_proceeds == 0;
                        if($puidUser->is_proceeds == 1 && $puidUser->level >= 1 && ($puidUser->level > $userModel->level || $volumeBool )  ){
                            // 如果为VIP用户分享且符合  比例大于0 ，此处是千分之
                            if($volumeBool && $userShareOrderOneModel->p_volume_share_ratio > 0){
                                if($orderInfoModel['json'] && isset($orderInfoModel['json']['good_attr']['price']) && $orderInfoModel['json']['good_attr']['price'] > 0){
                                    $total = $bc->calcDiv($bc->calcMul($orderInfoModel['json']['good_attr']['price'],$userShareOrderOneModel->p_volume_share_ratio),1000,2);
                                    $desc_str .= "-VIP用户分享";
                                }
                                // 层级高的用户分享
                            }else{
                                // 当前用户自购省的金额
                                $userTotal = 0;$total = 0;$upidShareTotal =0;
                                if(isset($userLevelAllList[$userModel['level']]))
                                    $userTotal = $bc->calcDiv($shareAmount * $userLevelAllList[$userModel['level']]['purchase'],100,2);
                                // 分享者 分享赚的钱
                                if(isset($userLevelAllList[$puidUser->level]))
                                    $upidShareTotal = $bc->calcDiv($shareAmount * $userLevelAllList[$puidUser->level]['share'],100,2);
                                if($upidShareTotal > 0)
                                    $total = $upidShareTotal - $userTotal;
                                $desc_str .= "-层级用户分享";
                            }
                            // 如果符合大于0
                            if($total > 0){
                                # 插入喵呗记录表
                                $puid_num = $puidUser['id'];
                                $miaoLogData['money'] = $shareAmount * 100;
                            }
                        }
                        // 直播商品购买  直播商品分享等
                    }else if($orderInfoModel->switch_num == 6 && isset($orderInfoModel['json']['lives']) && is_array($orderInfoModel['json']['lives'])){
                        // 进行关联到 直播商品订单表
                        $liveBroadcastOrderId = LiveBroadcastOrder::insert([
                            'live_goods_id'  => $orderInfoModel['json']['lives']['live_goods_id'],
                            'live_price' => $orderInfoModel['json']['lives']['live_price'],
                            'commission' => $bc->calcDiv($userShareOrderOneModel->miao,100,2) ,//$orderInfoModel['json']['lives']['commission'],
                            'commission_rato' => $orderInfoModel['json']['lives']['commission_rato'],
                            'add_time'  => time()
                        ]);
                        # 直播商品销量加 1
                        LiveBroadcastGoods::where('id',$orderInfoModel['json']['lives']['live_goods_id'])->inc('sales_volume',isset($orderInfoModel['json']['num']) ? $orderInfoModel['json']['num'] : 1)->update();
                        # 直播列表详情数据操作
                        $liveBroadcastInfoOne = LiveBroadcastInfo::where('live_id',$userShareOrderOneModel->related_id)->find();
                        $total = $userShareOrderOneModel->miao;
                        LiveBroadcastInfo::where('live_id',$userShareOrderOneModel->related_id)->update([
                            'order_num' => $liveBroadcastInfoOne->order_num + 1,
                            'miao'  => $bc->calcAdd($liveBroadcastInfoOne->miao,$orderInfoModel['json']['lives']['commission']),
                            'money' => $bc->calcAdd($liveBroadcastInfoOne->money,$orderInfoModel['json']['lives']['live_price'] * $orderInfoModel['json']['num'])
                        ]);
                        $puid_num =$liveBroadcastInfoOne->uid;
                        fileLog('支付类型---'.$orderInfoModel->switch_num.'-----主播用户id'.$liveBroadcastInfoOne->uid,'直播.log');
                    }

                    #分享赚（分享者）金额大于自购省（购买者）金额则新增分佣记录
                    # 或者当前 有佣金的情况下  直播分享购买
                    if ($total > 0 && $puid_num > 0) {
                        fileLog('流程bool----'.((int)$orderInfoModel->switch_num == 6),'直播.log');
                        // 直播商品-直播分享
                        if((int)$orderInfoModel->switch_num == 6){
                            fileLog('支付类型---'.$puid_num,'直播.log');
                            LiveMiaoLog::insertGetId([
                                'uid' => $puid_num,
                                'oid' => $orderOrnModel->id,
                                'live_id' => $userShareOrderOneModel->related_id,
                                'reward' => $bc->calcDiv($total,100,2),
                                'add_time' => time()
                            ]);
                            # 进行对应直播列表中的详情数据统计数据

                        // 分享商品-视频分享商品
                        }else{
                            $miaoLogData['type'] = 4;
                            $miaoLogData['uid'] = $puid_num;
                            $miaoLogData['reward'] = $total * 100;
                            $log_id = $miaoLogModel->insertGetId($miaoLogData);
                            # 写入到  钱包 待结算 中
                            $userWalletOneModel = UserWallet::where('uid', $puid_num + 0)->lock(true)->find();
                            if($userWalletOneModel){
                                $userWalletOneModel->pre_miao += $total * 100;$userWalletOneModel->save();
                                # 钱包记录
                                $WalletOperationLogData = ['uid'=>$userModel->id,'reward'=> $total * 100,'status'=>1,'type'=>2,'extend'=>'order','extend_id'=>$orderOrnModel->id,'describe'=>'订单支付-分享赚-'.$orderInfoModel->switch_num,'add_time'=>$time];
                                WalletOperationLog::insertGetId($WalletOperationLogData);
                                fileLog('分享---写入钱包，操作'.json_encode($WalletOperationLogData),'PayOrderEnd.log');
                            }
                        }
                    }


                    // 用户订单分享表
                    $userShareOrderOneModel->status = 2;$userShareOrderOneModel->pay_time = $time;$userShareOrderOneModel->desc = $desc_str.'ok';
                    $userShareOrderOneModel->p_share_money = isset($upidShareTotal) ? $upidShareTotal * 100: 0;
                    // 如果是分享且不是直播
                    if((int)$orderInfoModel->switch_num != 6){
                        $userShareOrderOneModel->miao =  isset($total) ? $total * 100: 0;
                    }
                    $userShareOrderOneModel->save();
                    Log::write("\t\t订单id".$orderOrnModel->id."\r\n分享点击-".$userShareOrderOneModel->desc."-处理完毕",'huiDiao');
                    break;
                // 其他情况 不处理
                default:
                    break;
            }

            # 商品中的操作 销量加1  且 判断是否为锁定库存操作
            if($orderInfoModel['json'] && isset($orderInfoModel['json']['good_attr']) && $orderInfoModel['json']['good_attr'] && isset($orderInfoModel['json']['good_attr']['product_id'])){
                Log::write("\t\t订单id".$orderOrnModel->id."\r\n商品拍下减库存-处理开始",'huiDiao');
                $goodsModel = Goods::find($orderInfoModel['json']['good_attr']['product_id']);
                $num = isset($orderInfoModel['json']['num']) ? $orderInfoModel['json']['num'] : 1;
                // 商品
                if($goodsModel){
                    // 如果是 付款减库存
                    Goods::where('id',$goodsModel->id)->update([
                        "sales_volume" => $goodsModel->sales_volume + $num,
                        "stock" => $goodsModel->is_stock == 2 ? ($goodsModel->stock - $num > 0 ? $goodsModel->stock - $num : 0) : $goodsModel->stock,
                        "sale" => $goodsModel->sale + $num
                    ]);
                    // 商品规格减库存
                    $goodsAttrModel = GoodsAttr::find($orderInfoModel['json']['good_attr']['id']);
                    if($goodsAttrModel){
                        // 如果是 付款减库存
                        GoodsAttr::where('id',$goodsAttrModel->id)->update([
                            "stock" => $goodsModel->is_stock == 2 ? ($goodsModel->stock - $num > 0 ? $goodsModel->stock - $num : 0) : $goodsModel->stock,
                            "sale" => $goodsAttrModel->sale + $num
                        ]);
                    }
                }
                Log::write("\t\t订单id".$orderOrnModel->id."\r\n商品拍下减库存-处理完毕",'huiDiao');
            }
            fileLog(date('y-m-d h:i:s').'---微信支付-回调ok-推送---团队结算队列...11111111111111111----'.$teamAmount,date('Y-m-d').'_wechat_pay.log');
            #  只有有付款 而且开启团队-    订单中包含累计消费商品 - 团队分佣  = 实际支付金额*团队收益
            if($teamAmount && count($teamOrder)){
//                $orderModel = Order::find(182);
//                $orderGoodsModelArrs = OrderGoods::where('order_id',$orderModel->id)->select();
//                $teamOrder = [];
//                foreach($orderGoodsModelArrs as $k=>$v)
//                    if($v['is_team'] == 1 ) $teamOrder[] = $v;
                $data = ['uid' => $userModel->id, 'order' => $teamOrder];
                $b = MyJob::pushQueue('TeamSettlementJob',$data,30);
                fileLog(date('y-m-d h:i:s').'---微信支付-回调ok-推送---团队结算队列...'.$b,date('Y-m-d').'_wechat_pay.log');
//                $total = $teamAmount * ($userLevelAllList[$userModel['level']]['team'] / 100);
                #团队累计消费
//                if($total > 0){
//                    $miaoLogData['type'] = 3;$miaoLogData['uid'] = $userModel->id;$miaoLogData['reward'] = $total;$miaoLogData['money'] = $teamAmount;$log_id = $miaoLogModel->insertGetId($miaoLogData);
//                    Log::write("\t\t订单id".$orderOrnModel->id."\r\n记录团队消费ok-处理完毕",'huiDiao');
//                }
            }

            # 设置订单状态
            // 更新时间-订单中的信息 // 设置状态 已完成
            $orderOrnModel->pay_time =  $time;$orderOrnModel->status = 2;$orderOrnModel->save();

            // 商品
            if(!isset($goodsModel) || !isset($goodsModel->name)){
                $goodsModel = Goods::find($orderInfoModel['json']['good_attr']['product_id']);
            }
            $wxModel = new WxApi();
            # 添加推送内容信息
            $wxModel->wxaTemplate($userModel,[
                'tid' =>  'FddT6-1bVu2lfiggUR7FVmS0mwrvTlGIgksy6xh94XE',
                'order_sn' => $orderOrnModel->order_sn,
                'goods_name' => $goodsModel->name,
                'total_amount' => $orderInfoModel['json']['good_attr']['cost_price'],
                'pay_amount' => $orderOrnModel->total / 100,
            ]);
            // 提交事务
            $this::commit();
            Log::write('----所有逻辑已经跑通了----'.$orderOrnModel->order_sn,'huiDiao');
            return $list;
        }catch (Exception $e){
            Db::rollback();
            fileLog(date('y-m-d h:i:s').'---回滚----'.$e->getMessage().$teamAmount,date('Y-m-d').'_wechat_pay.log');
            return $list;
        }
    }

    /**
     * 模型关联一对一 订单详情
     */
    public function oneOrderInfo()
    {
        return  $this::hasOne(OrderInfo::class,'oid','id');
    }

    /**
     * 模型关联一对多  订单-订单商品
     */
    public function manyOrderGood()
    {
        return  $this::hasMany(OrderGoods::class,'order_id','id');
    }

    /**
     * 模型关联收货地址 收货地址
     */
    public function oneUserAddress()
    {
        return  $this::hasOne(UserAddress::class,'id','addr_id');
    }

    /**
     * 模型关联收货地址 物流信息
     */
    public function oneExpress()
    {
        return  $this::hasOne(Express::class,'id','express_id');
    }

}
